<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100">
            <el-form-item label="落地页名称" prop="linkName">
              <el-input v-model="queryParams.linkName" placeholder="请输入落地页名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable >
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="页面模式" prop="pageMode">
              <el-select v-model="queryParams.pageMode" placeholder="请输入页面模式" clearable >
                <el-option v-for="dict in bus_spread_link_page_mode" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bus:jqtSpreadLink:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['bus:jqtSpreadLink:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['bus:jqtSpreadLink:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="jqtSpreadLinkList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="唯一ID" align="center" prop="id" v-if="false" />
        <el-table-column label="站点信息" align="center" prop="linkName">
          <template #default="scope">
            <p>{{scope.row.linkName}}</p>
            <p>{{scope.row.createTime}}</p>
          </template>
        </el-table-column>
        <el-table-column label="投放链接" align="center" prop="spreadUrl">
          <template #default="scope">
            <p>http://baidu.com/{{scope.row.spreadUrl}}</p>
          </template>
        </el-table-column>
        <el-table-column label="页面模式" align="center" prop="pageMode">
          <template #default="scope">
            <dict-tag :options="bus_spread_link_page_mode" :value="scope.row.pageMode"/>
          </template>
        </el-table-column>
        <el-table-column label="跳转类型" align="center">
          <template #default="scope">
            <dict-tag :options="bus_skip_set_type" :value="scope.row.skipSet?.type"/>
          </template>
        </el-table-column>
        <el-table-column label="回传平台" align="center">
          <template #default="scope">
            <div v-if="adver_back_type" style="font-size: 10px;color: black;">
              <span style="display: block; margin: 1px 0;">{{getLabelByValue(adver_back_type,scope.row.adverBack.platformInfo.type)}}</span>
              <div v-for="item in scope.row.adverBack.adverBackEvent" >
                <span style="display: block; margin: 1px 0;" v-if="item.event !=='0'">
                {{getLabelByValue(adver_back_user_action,item.userAction)}}
              </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column key="status" label="页面状态" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="所属用户" align="center">
          <template #default="scope">
            <span>{{scope.row.userName}}({{scope.row.nickName}})</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="编辑内容" placement="top">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['bus:jqtSpreadLink:edit']">编辑内容</el-button>
            </el-tooltip>
            <el-tooltip content="复制页面" placement="top">
              <el-button link type="primary" @click="handleCopy(scope.row)" v-hasPermi="['bus:jqtSpreadLink:edit']">复制页面</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['bus:jqtSpreadLink:remove']">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 新增推广链模式 -->
    <el-dialog :title="dialogMode.title" v-model="dialogMode.visible" width="1000px" append-to-body>
      <el-row :gutter="20">

        <el-col :span="6" v-for="item in modeTypes" :key="item.value">
          <!-- 卡片外层容器，用于添加边框和阴影 -->
          <div class="card-wrapper">
            <div class="image-container">
              <el-image :src="item.img" style="border-radius: 8px;" fit="cover">
                <!-- 添加的按钮 -->
                <template #placeholder>
                  <div class="image-slot">
                    Loading<span class="dot">...</span>
                  </div>
                </template>
                <template #error>
                  <div class="image-slot">
                    Error
                  </div>
                </template>
              </el-image>
              <button class="centered-button" @click="handleSpreadLink(item)">创建链接</button>
            </div>
            <!-- 标题与副标题 -->
            <div class="text-container">
              <div class="title">{{ item.label }}</div>
              <div class="subtitle">{{ item.subtitle }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="JqtSpreadLink" lang="ts">
import {
  listJqtSpreadLink,
  getJqtSpreadLink,
  delJqtSpreadLink,
  addJqtSpreadLink,
  updateJqtSpreadLink,
  changeStatus, copyLink
} from '@/api/bus/jqtSpreadLink';
import { JqtSpreadLinkVO, JqtSpreadLinkQuery, JqtSpreadLinkForm } from '@/api/bus/jqtSpreadLink/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable,
  bus_spread_link_page_mode,
  adver_back_type,
  adver_back_user_action,
  bus_skip_set_type
} = toRefs<any>(proxy?.useDict('sys_normal_disable','bus_spread_link_page_mode','adver_back_type','adver_back_user_action','bus_skip_set_type'));
import s1 from '@/assets/images/spreadLinkMode/s1.png'
import s2 from '@/assets/images/spreadLinkMode/s2.png'
import s3 from '@/assets/images/spreadLinkMode/s3.png'
import s4 from '@/assets/images/spreadLinkMode/s4.png'
import { UserVO } from '@/api/system/user/types';
import api from '@/api/system/user';
import { authUnlock } from '@/api/system/social/auth';
const jqtSpreadLinkList = ref<JqtSpreadLinkVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const dialogMode = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 推广链模式
const modeTypes = [
  {
    label: '图片模式',
    subtitle: '点击后直接跳转企业微信',
    value: '1001',
    img: s1
  },
  {
    label: '图文交互模式',
    subtitle: '图文展示+跳转',
    value: '1002',
    img: s2
  },
  {
    label: '问答模式',
    subtitle: '自定义问答交互流程',
    value: '1003',
    img: s3
  },
  {
    label: '关键回复模式',
    subtitle: '关键词回复仿客服聊天',
    value: '1004',
    img: s4
  }
]


const data = reactive<PageData<JqtSpreadLinkForm, JqtSpreadLinkQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    linkName: undefined,
    spreadUrl: undefined,
    status: undefined,
    pageMode: undefined,
    pageModeContent: undefined,
    skipSet: undefined,
    adverBack: undefined,
    adverBackRatio: undefined,
    adverBackAuto: undefined,
    params: {
    }
  },
  rules: {
  }
});

const { queryParams} = toRefs(data);

/** 查询推广链接列表 */
const getList = async () => {
  loading.value = true;
  const res = await listJqtSpreadLink(queryParams.value);
  jqtSpreadLinkList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  dialogMode.visible = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: JqtSpreadLinkVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  dialogMode.visible = true;
  dialogMode.title = "选择模板";
}


/** 删除按钮操作 */
const handleDelete = async (row?: JqtSpreadLinkVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除推广链接编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delJqtSpreadLink(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('bus/jqtSpreadLink/export', {
    ...queryParams.value
  }, `jqtSpreadLink_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});

onActivated(() => {
  getList();
})
/**
 * 点击创建推广链模式
 * @param item
 */
const handleSpreadLink = (item:any,id?:string|number) =>{
  if(id){
    proxy.$router.push({
      name: 'SpreadLinkWithId',
      params: {
        mode: item.value,
        id: id
      }
    })
  }else{
    proxy.$router.push({
      name: 'SpreadLink',
      params: {
        mode: item.value
      }
    })
  }
  cancel();
}
//修改按钮操作
const handleUpdate = async (row?: JqtSpreadLinkVO) => {
  //从modeTypes根据value获取
  const item = modeTypes.find(item => item.value === row.pageMode);
  handleSpreadLink(item,row?.id)
};
//复制链接
const handleCopy = async (row?: JqtSpreadLinkVO) => {
  await proxy?.$modal.confirm('您确定要复制"' + row.linkName + '"的链接吗？');
  await copyLink(row.id);
  proxy?.$modal.msgSuccess("复制成功");
  await getList();
}

/**
 * 根据value获取label
 * @param data
 * @param value
 */
const getLabelByValue = (data:any,value: string) => {
  const item = data.find(item => item.value === value);
  return item ? item.label : '--';
};

/** 用户状态修改  */
const handleStatusChange = async (row: JqtSpreadLinkVO) => {
  const text = row.status === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.linkName + '"页面吗?');
    await changeStatus(row.id, row.status);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch (err) {
    row.status = row.status === '0' ? '1' : '0';
  }
};
</script>

<style scoped>

.card-wrapper {
  border: 1px solid #e4e4e4; /* 边框 */
  border-radius: 10px; /* 圆角配合图片一致 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* 阴影 */
  padding: 10px;
  background-color: #fff;
  transition: box-shadow 0.3s ease;
}

.card-wrapper:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12); /* 悬浮时阴影变大 */
}

.image-container {
  position: relative;
  width: 100%;
}

.centered-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.text-container {
  text-align: center;
  margin-top: 8px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 黑色标题 */
}

.subtitle {
  font-size: 14px;
  color: #666; /* 灰色副标题 */
  margin-top: 4px;
}
</style>
